package edu.unicen.compilers.polish;

import java.text.DecimalFormat;
import java.util.Vector;

public class Function {
	Vector<EntryPoint> entryPoints;
	Vector<String> vars= new Vector<String>();
	String prefix;	
	private Vector<String> vector=new Vector<String>();
	private Vector<Integer> pila=new Vector<Integer>();
	private Vector<Integer> pila_for=new Vector<Integer>();
	private Vector<Integer> unresolvedBi=new Vector<Integer>();
	private int lastComplete=0;
	
	public Function() {
		this.entryPoints = new Vector<EntryPoint>();
	}
	
	public Function(String p) {
		this.prefix = p;
		this.entryPoints = new Vector<EntryPoint>();
	}
	
	public void addVar(String v){
		if (!vars.contains(v))
			this.vars.add(this.prefix+v);
	}
	public void add(String lexeme){
		if (vars.contains(this.prefix+lexeme))
			vector.add(this.prefix+lexeme);
		else
			vector.add(lexeme);
	}
	
	public void resolveJump(){
		DecimalFormat df = new DecimalFormat("######");
		lastComplete=pull();
		vector.set(lastComplete,  "_L"+prefix+df.format(this.vector.size()));
	}
	
	public void insertBI(){
		DecimalFormat df = new DecimalFormat("######");
		String a= vector.elementAt(lastComplete);
		Double ant= Double.valueOf(a.substring(3)) + 2;
		vector.set(lastComplete, "_L"+prefix+df.format(ant));
		vector.add("");
		push();
		vector.add("BI");
	}
	
	public void insertBIFor(){
			DecimalFormat df = new DecimalFormat("######");
			Integer bi=pila_for.remove(pila_for.size()-1)+1;
			//TODO: ADD TO FUNCTIONS
			unresolvedBi.add(bi);
			vector.add("_L"+prefix+df.format(bi));
			vector.add("BI");
	}
	
	public void push(){
		pila.add(vector.size()-1);
		
	}
	public void pushFor(){
		pila_for.add(vector.size()-1);
		
	}
	
	public Integer pull(){
		return pila.remove(pila.size()-1);
	}

	public void addEntryPoint(String name) {
		entryPoints.add(new EntryPoint(name));		
	}
	
	public void endEntryPoint() {
		
		entryPoints.elementAt(entryPoints.size()-1).setPolish(this.vector);
		entryPoints.elementAt(entryPoints.size()-1).setUnresolverdIB(this.unresolvedBi);
		this.unresolvedBi=new Vector<Integer>();
		this.vector= new Vector<String>();
	}

	@Override
	public String toString() {
		StringBuffer sb=new StringBuffer();
		sb.append("Nombre "+ prefix + " \n");
		//sb.append("Vars "+ vars + " \n");
		for (EntryPoint entry : this.entryPoints) {
			sb.append(entry+" \n");	
		}
		return sb.toString();
	}

	public boolean existVar(String key) {
		return this.vars.contains(key);
	}

	public String getPrefix() {
		return this.prefix;
	}

	public Vector<String> getVars(){
		return this.vars;
	}

	public Vector<EntryPoint> getEntryPoints() {
		
		return this.entryPoints;
	}
	
	public void closeFunction(){
		EntryPoint lastPoint=this.entryPoints.elementAt(this.entryPoints.size()-1);
		if (! lastPoint.getPolish().elementAt(lastPoint.getPolish().size()-1).equalsIgnoreCase("return") ){
			lastPoint.getPolish().add("0");
			lastPoint.getPolish().add("RETURN");
		}
	}
}
